package com.soundfrequencyapp.actions;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

import com.soundfrequencyapp.R;

public class ImageActivity extends Activity {

	public static final String EXTRA_IMAGE_ID = "filename";
	private final int timeToLive = 5000;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.screen_activity_show_image);
		
		handleIntent(getIntent());
		
		scheduleFinish();
	}
	
	private void handleIntent(Intent i) {
		if (i != null) {
			int imageId = i.getIntExtra(EXTRA_IMAGE_ID, 0);
			ImageView imgv = (ImageView) findViewById(R.id.imgv);
			imgv.setImageBitmap(loadImageFromRaw(imageId));
		}
	}
	
	private Bitmap loadImageFromRaw(int imageId) {
		InputStream is = null;
		Bitmap bitmap = null;
		try {
			is = getResources().openRawResource(imageId);
		} catch (Exception e1) {  
			e1.printStackTrace();
		} finally {
			try {
				if (is != null) {
					bitmap = BitmapFactory.decodeStream(is);
				}
				is.close();
				is = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bitmap;
	}
	
	private void scheduleFinish() {
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			
			public void run() {
				ImageActivity.this.finish();
			}
		};
		if (timer != null) {
			timer.schedule(task, timeToLive);
		}
	}
	
}
